# app/routes/favorite_routes.py
from flask import Blueprint, redirect, url_for, request, render_template
from flask_login import login_required, current_user
from app.models.favorite import Favorite
from app.models.movie import Movie

favorite_bp = Blueprint('favorite', __name__)

@favorite_bp.route('/favorite/add/<int:movie_id>', methods=['POST'])
@login_required
def add_favorite(movie_id):
    movie = Movie.get_or_none(Movie.id == movie_id)
    if movie and not Favorite.select().where(
        (Favorite.user == current_user.id) & (Favorite.movie == movie_id)).exists():
        Favorite.create(user=current_user.id, movie=movie_id)
    return redirect(request.referrer or url_for('auth.home'))

@favorite_bp.route('/favorite/remove/<int:movie_id>', methods=['POST'])
@login_required
def remove_favorite(movie_id):
    Favorite.delete().where((Favorite.user == current_user.id) & (Favorite.movie == movie_id)).execute()
    return redirect(request.referrer or url_for('auth.home'))

@favorite_bp.route('/favorites')
@login_required
def list_favorites():
    favorites = (Movie
                 .select()
                 .join(Favorite)
                 .where(Favorite.user == current_user.id)
                 .order_by(Movie.title))
    return render_template('favorites.html', username=current_user.username, favorites=favorites)
